package com.itcncp.ucenter.rpc.service.impl;

import com.itcncp.common.annotation.BaseService;
import com.itcncp.common.base.BaseServiceImpl;
import com.itcncp.common.model.OrderCodeType;
import com.itcncp.common.rongCloud.models.SdkHttpResult;
import com.itcncp.common.rongCloud.models.SdkHttpResultToken;
import com.itcncp.common.util.AESUtil;
import com.itcncp.common.util.JsonUtils;
import com.itcncp.common.util.OrderUtils;
import com.itcncp.common.util.rongCloud;
import com.itcncp.ucenter.dao.mapper.UserAccountInfoMapper;
import com.itcncp.ucenter.dao.mapper.UserCustomerInfoMapper;
import com.itcncp.ucenter.dao.mapper.UserRechangeOpJnlMapper;
import com.itcncp.ucenter.dao.model.UserAccountInfo;
import com.itcncp.ucenter.dao.model.UserCustomerInfo;
import com.itcncp.ucenter.dao.model.UserCustomerInfoExample;
import com.itcncp.ucenter.dao.model.UserRechangeOpJnl;
import com.itcncp.ucenter.rpc.api.UserCustomerInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
* UserCustomerInfoService实现
* Created by itcncp on 2018/1/12.
*/
@Service
@Transactional
@BaseService
public class UserCustomerInfoServiceImpl extends BaseServiceImpl<UserCustomerInfoMapper, UserCustomerInfo, UserCustomerInfoExample>
        implements UserCustomerInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserCustomerInfoServiceImpl.class);

    @Autowired
    UserCustomerInfoMapper userCustomerInfoDao;

    @Autowired
    UserAccountInfoMapper userAccountInfoDao;

    @Autowired
    UserRechangeOpJnlMapper userRechangeOpJnlDao;


    public  boolean isMobile(String mobile){
        //判断改手机号是否被注册
        UserCustomerInfo  total =  getUserInfoByMobile(mobile);

        if (null!=total) {
            return true;
        }
        return false;
    }

    //根据手机号查找用户信息
    private  UserCustomerInfo getUserInfoByMobile(String mobile){
        //判断改手机号是否被注册
        UserCustomerInfoExample userInfoExampleMobile = new UserCustomerInfoExample();

        userInfoExampleMobile.createCriteria().andMobileEqualTo( mobile ).andStatusEqualTo(new Byte("1"));

        List<UserCustomerInfo> total = userCustomerInfoDao.selectByExample( userInfoExampleMobile );

        if (null!=total && total.size()> 0) {
            return total.get( 0 );
        }
        return null;
    }


    /**
     * 验证请求接口是否过期
     * @param userId
     * @param deviceAppNo
     * @param token
     * @return
     */
    @Override
    public boolean UserTokenExpired(Long userId,String deviceAppNo,String token){

        UserCustomerInfo userCustomerInfo = userCustomerInfoDao.selectByPrimaryKey(userId);

        if(null != userCustomerInfo){
            if(null != userCustomerInfo.getDeviceAppNo() && null != userCustomerInfo.getToken()){


                System.out.println("detoString())"+userCustomerInfo.getDeviceAppNo().toString().equals(deviceAppNo.toString()));

                System.out.println("tokenString())"+userCustomerInfo.getToken().toString().equals(token.toString()));


                if(userCustomerInfo.getDeviceAppNo().toString().equals(deviceAppNo.toString())
                  && userCustomerInfo.getToken().toString().equals(token.toString())){
                    return  false;
                }
            }
        }

        return true;
    }

    @Override
    public UserCustomerInfo registerInfo(UserCustomerInfo userCustomerInfo) {

        if(isMobile( userCustomerInfo.getMobile() )){
            return  null;
        }

        //初始化添加用户信息
        // 注册融云帐号
            SdkHttpResult sdkRong = rongCloud.getToken(userCustomerInfo.getDeviceAppNo(),
                userCustomerInfo.getNickname(), userCustomerInfo.getHead());
        // 解析得到的数据
        SdkHttpResultToken token = JsonUtils.toBean(sdkRong.getResult(),
                SdkHttpResultToken.class);
        // 更新用户当前登录的设备信息
        userCustomerInfo.setToken(token.getToken());
        userCustomerInfo.setUserId( OrderUtils.createOrderId( OrderCodeType.USER_ID ) );
        userCustomerInfo.setCreateTime( new Date(  ) );
        userCustomerInfo.setUpdateTime( new Date(  ) );

        //设置用户安全码
        userCustomerInfo.setSecurity( AESUtil.encryptPassword( userCustomerInfo.getSecurity() ) );

        //用户类型 用户类型 1-个人，2-单位 前期默认位个人
        userCustomerInfo.setAgentIdType( Byte.valueOf( "1" ));

        //用户状态(1.正常，2.锁定)
        userCustomerInfo.setStatus(   new Byte( "1" ));

        //扣款方式 扣款方式 1非自动扣款 2自动扣款（不需要密码）
        userCustomerInfo.setPayMethod( new Byte( "1" ));

        //我的发票数量
        userCustomerInfo.setInvoiceCnt( new Byte( "5" ));

        //银行卡绑定数量
        userCustomerInfo.setBankcardCnt( new Byte( "5" ));

        //通行缴费是否自动开票 1是 2否
        userCustomerInfo.setInvoiceAutoFlag( new Byte( "1" ) );

        //密码加密
        userCustomerInfo.setPassword( AESUtil.encryptPassword( userCustomerInfo.getPassword() ) );

        userCustomerInfoDao.insert( userCustomerInfo );

        //添加账户系统
        UserAccountInfo userAccountInfo = new UserAccountInfo();
        userAccountInfo.setUserId( userCustomerInfo.getUserId() );
        //账户状态   1、正常   2、锁定
        userAccountInfo.setAccountState( new Byte( "1" ) );
        //账户余额
        userAccountInfo.setAccountBalance( new BigDecimal( "0" ) );
        //账户类型 1、个人账户 2、企业账户
        userAccountInfo.setAccountType( new Byte( "1" ) );
        //信用金额
        userAccountInfo.setCreditMoney( new BigDecimal( "0" ) );
        //服务费金额
        userAccountInfo.setServiceFee( new BigDecimal( "0" ) );
        //等级日期
        userAccountInfo.setAccountRegisteDate( new Date(  ) );

        userAccountInfoDao.insert( userAccountInfo );

        //开户记录，存入一份至充值流水表中

        UserRechangeOpJnl userRechangeOpJnl = new UserRechangeOpJnl();

        userRechangeOpJnl.setRechargeNo( OrderUtils.createOrderId( OrderCodeType.RECHARGE_NO ) );
        userRechangeOpJnl.setUserId( userCustomerInfo.getUserId() );
        userRechangeOpJnl.setdOrderNo( "" );
        //充值方式 1、微信 2、支付宝 3、银联 4、银行卡 5、其他
        //开户默认位ITC 其他方式
        userRechangeOpJnl.setRechargeWay( new Byte( "5" ));
        //充值金额
        userRechangeOpJnl.setRechargeAmount( new BigDecimal( "0" ) );
        //实收金额
        userRechangeOpJnl.setRechargeActAmount( new BigDecimal( "0" ) );
        //充值费率
        userRechangeOpJnl.setRechargeFee( new BigDecimal( "0" ) );
        //充值状态  1、失败； 2、成功
        userRechangeOpJnl.setRechargeState( new Byte( "2" ) );
        //充值前账户余额
        userRechangeOpJnl.setOldBalance( new BigDecimal( "0" ) );
        //充值后账户余额
        userRechangeOpJnl.setNowBalance( userAccountInfo.getAccountBalance() );

        userRechangeOpJnl.setRemark( "用户注册开户，充值记录金额默认0元" );

        userRechangeOpJnlDao.insert( userRechangeOpJnl );

        return userCustomerInfo;
    }

    @Override
    public UserCustomerInfo login(UserCustomerInfo userCustomerInfo) {

        //根据手机号查询用户信息
        UserCustomerInfo itemUserInfo  = getUserInfoByMobile( userCustomerInfo.getMobile() );

        //判断账户是否存在
        if(null != itemUserInfo && null != itemUserInfo.getUserId() && itemUserInfo.getStatus()==1){

            String loginPassword = AESUtil.encryptPassword( userCustomerInfo.getPassword() );

            if (!itemUserInfo.getPassword().equals( loginPassword )) {
                // 帐号或密码错误
                return null;
            }

            String deviceId = userCustomerInfo.getDeviceAppNo();
            /**
             * 先判断当前设备id与之前的设备id是否一致 一致则不需要重新获取 不一致则可能该用户在其他设备上进行登录，token重新获取
             * 保证其他设备不会收到通知
             */
            /**
             * 更换生产环境推送  || deviceId.length()>1 第一次使用，过段时间这个判断将清除
             */
            if (!deviceId.equals(itemUserInfo.getDeviceAppNo())) {
                // 登陆后注册融云
                SdkHttpResult resutl = rongCloud.getToken(deviceId,itemUserInfo.getNickname(), itemUserInfo.getHead());
                // 解析得到的数据
                SdkHttpResultToken token = JsonUtils.toBean(resutl.getResult(),SdkHttpResultToken.class);
                // 更新用户当前登录的设备信息
                itemUserInfo.setToken(token.getToken());
                itemUserInfo.setDeviceAppNo( deviceId );
            }

            //更新经纬度
            if(null != userCustomerInfo.getLatitude() && null != userCustomerInfo.getLongitude()){
                itemUserInfo.setLatitude( userCustomerInfo.getLatitude() );
                itemUserInfo.setLongitude( userCustomerInfo.getLongitude() );
            }

            //更新用户信息
            itemUserInfo.setUpdateTime( new Date(  ) );

            Integer total =  userCustomerInfoDao.updateByPrimaryKeySelective( itemUserInfo );

            if(total>0){
                return  itemUserInfo;
            }

            return null;

        }

        return null;
    }



}